import React, { FC, useState } from "react";
import styles from "./commonList.module.scss";
import {
  Table,
  Empty,
  Typography,
  Tag,
  Button,
  Space,
  Modal,
  Spin,
  message,
} from "antd";
import { useTitle } from "ahooks";
import { ExclamationCircleOutlined } from "@ant-design/icons";
import SearchList from "../../components/SearchList";
import ListPagination from "../../components/ListPagination";
import { useRequest } from "ahooks";
import { updataIsStarOrDelt, completDelete } from "../../services/question";

// 使用自定义hook请求列表数据
import useLoadQuestionListData from "../../hooks/useLoadingQuestionListData";

const { confirm } = Modal;

// dataIndex : 表示要从数据源数组中取那个字段的值
// key : 当前列的id , 不设置默认去dataIndex 的值
const colums = [
  {
    title: "标题",
    dataIndex: "title",
    // key : "title"
  },
  {
    title: "是否发布",
    dataIndex: "isPublished",
    render: (isPublished: boolean, rowDate: any) => {
      // console.log("rowkey", rowDate);
      return isPublished ? (
        <Tag color="#2db7f5">已发布</Tag>
      ) : (
        <Tag color="#f50">未发布</Tag>
      );
    },
  },
  {
    title: "答卷数量",
    dataIndex: "answerCount",
  },
  {
    title: "创建时间",
    dataIndex: "createAt",
  },
];
const { Title } = Typography;

const Trash: FC = () => {
  // let [list, setList] = useState(rawQuestionList);
  // 记录选中的ID
  let [selectedId, setSelectedId] = useState<string[]>([]);

  const {
    data = {},
    loading,
    refresh,
  } = useLoadQuestionListData({ isDelete: true });
  const { list = [], total = 0 } = data;
  useTitle("鸣远问卷 - 回收站");

  const del = () => {
    confirm({
      title: "确认彻底删除该问卷？",
      icon: <ExclamationCircleOutlined />,
      content: "删除以后不可以找回！",
      okText: "确认",
      cancelText: "取消",
      onOk: () => {
        deleteRequest()
      },
    });
  };

  // 恢复功能和列表问卷中的删除是相对应的： 不是真的删除，而是通过修改删除字段的标识控制当前卡片展示位置：我的问卷/回收站
  const { loading: recoverying, run: recover } = useRequest(
    async () => {
      for (let val of selectedId) {
        await updataIsStarOrDelt(val, { isDelete: false });
      }
    },
    {
      manual: true,
      debounceWait: 500, // useRequest 自带的防抖方法，在调用run方法时会自动防抖
      onSuccess() {
        message.success("恢复成功");
        // 手动刷新
        refresh();
        // 重新获取列表之后，选中项应当清空
        setSelectedId([])
      },
    }
  );

  // 彻底删除
  const { loading: delLoading, run: deleteRequest } = useRequest(
    async () => {
      return await completDelete(selectedId);
    },
    {
      manual: true,// 设置手动调用，则下面的处理在手动调用run之后执行
      debounceWait: 500,
      onSuccess() {
        message.success("彻底删除成功");
        // 
        refresh()
        setSelectedId([])
      },
    }
  );

  const tableElem = (
    <>
      <div style={{ marginBottom: "16px" }}>
        <Space>
          <Button
            type="primary"
            disabled={selectedId.length == 0}
            onClick={recover}
          >
            恢 复
          </Button>
          <Button danger disabled={selectedId.length == 0} onClick={del}>
            删 除
          </Button>
        </Space>
      </div>
      <Table
        rowKey={(q) => q._id}
        dataSource={list}
        columns={colums}
        pagination={false}
        rowSelection={{
          type: "checkbox",
          onChange: (selectedRowkeys): any => {
            console.log("selectedRowkeys", selectedRowkeys);
            setSelectedId(selectedRowkeys as string[]);
          },
        }}
      />
    </>
  );

  return (
    <>
      <div className={styles.header}>
        <div className={styles.left}>
          <Title level={3}>回收站</Title>
        </div>
        <div className={styles.right}>
          <SearchList />
        </div>
      </div>
      <div className={styles.content}>
        {loading && (
          <div style={{ textAlign: "center" }}>
            <Spin />
          </div>
        )}
        {!loading && list.length === 0 && <Empty description="暂无数据" />}
        {!loading && list.length && tableElem}
      </div>
      <div className={styles.footer}>
        <ListPagination total={total} />
      </div>
    </>
  );
};

export default Trash;
